package com.dmcb.common.business.utils;

import org.springframework.beans.factory.annotation.Autowired;
import sun.misc.BASE64Encoder;

import javax.script.ScriptException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * Created by a on 2015/3/12.
 */
public class TextUtil {

    @Autowired
    static RedisUtils redisUtils;

    public static String toString(byte[] bs) {
        return toString(bs, (String) null);
    }

    public static String toString(byte[] bs, String charset) {
        if (bs == null) {
            return null;
        }
        if (charset == null) {
            charset = "UTF-8";
        }
        try {
            return new String(bs, charset);
        } catch (UnsupportedEncodingException var3) {
            throw new RuntimeException(var3);
        }
    }

    public static byte[] toBytes(String s, String charset) {
        if (charset == null) {
            charset = "UTF-8";
        }
        try {
            return s.getBytes(charset);
        } catch (UnsupportedEncodingException var3) {
            throw new RuntimeException(var3);
        }
    }

    /**
     * 汉字数量统计
     *
     * @param text
     * @return
     */
    public int count(String text) {
        String Reg = "^[\u4e00-\u9fa5]{1}$";//正则
        int result = 0;
        for (int i = 0; i < text.length(); i++) {
            String b = Character.toString(text.charAt(i));
            if (b.matches(Reg)) result++;
        }
        return result;
    }

    /**
     * 获取随机字符串
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String encode(byte[] bytes) {
        return (new BASE64Encoder()).encode(bytes);
    }

    /*public static void main(String[] args) throws IOException, ScriptException, NoSuchMethodException {
        WebClientUtil webClientUtil = new WebClientUtil();
        WebClientUtil.wc =webClientUtil.initWc(false,false,true);
        System.out.println(WebUtil.buildRequest("https://www.toutiao.com/c/user/article/?page_type=1&user_id=5923803773&max_behot_time=0&count=20&as=A1A55BFEA931B4B&cp=5B7ED0AD05E4CE1&_signature=Jd-kNgAAfj7aIFvJpE7ityXfpC",true));

     // System.out.println(WebUtil.buildRequest("http://sh.qihoo.com/pc/detail?url=https%3A%2F%2Fwww.guancha.cn%2Flocal%2F2018_10_30_477545.shtml&check=65a87eb343da81e4&uid=ec87cbdf7ee8c60c5320a367bda98cc0&sign=360_e39369d1&scene=1&refer_scene=",false));

    }*/

}
